package com.poly.police.monitor.application.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.poly.police.monitor.application.mapper.sys.SysPermMapper;
import com.poly.police.monitor.application.mapper.sys.SysRoleMapper;
import com.poly.police.monitor.application.service.sys.ISysPermService;
import com.poly.police.monitor.common.util.StringUtils;
import com.poly.police.monitor.pojo.entity.sys.SysPerm;
import com.poly.police.monitor.pojo.entity.sys.SysRole;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * 系统权限服务实现类
 */
@Service
public class SysPermServiceImpl implements ISysPermService {

    @Resource
    SysPermMapper sysPermMapper;

    @Resource
    SysRoleMapper sysRoleMapper;

    /**
     * 根据角色ID获取菜单ID
     *
     * @param roleIds 角色ID
     * @return List<Integer>
     */
    @Override
    public List<Long> selectMenuIdsByRoleId(List<Long> roleIds) {
        List<Long> menus = new LinkedList<>();

        if (roleIds.isEmpty()) {
            return menus;
        }

        SysRole sysRole = sysRoleMapper.selectOne(new QueryWrapper<SysRole>()
                .in("id", roleIds)
                .eq("is_disable", 0)
                .last("limit 1"));

        if (StringUtils.isNull(sysRole)) {
            return menus;
        }

        List<SysPerm> sysPerms = sysPermMapper.selectList(
                new QueryWrapper<SysPerm>()
                        .in("role_id", roleIds));

        for (SysPerm sysPerm : sysPerms) {
            menus.add(sysPerm.getMenuId());
        }

        return menus;
    }

    /**
     * 批量写入角色菜单
     *
     * @author fzr
     * @param roleId 角色ID
     * @param menuIds 菜单ID组
     */
    @Override
    @Transactional
    public void batchSaveByMenuIds(Long roleId, List<Long> menuIds) {
        if (menuIds != null && !menuIds.equals("")) {
            menuIds.forEach(menuId -> {
                SysPerm model = new SysPerm();
                model.setRoleId(roleId);
                model.setMenuId(menuId);
                sysPermMapper.insert(model);
            });
        }
    }

    /**
     * 批量删除角色菜单(根据角色ID)
     *
     * @author fzr
     * @param roleId 角色ID
     */
    @Override
    public void batchDeleteByRoleId(Long roleId) {
        sysPermMapper.delete(new QueryWrapper<SysPerm>().eq("role_id", roleId));
    }

    /**
     * 批量删除角色菜单(根据菜单ID)
     *
     * @author fzr
     * @param menuId 菜单ID
     */
    @Override
    public void batchDeleteByMenuId(Long menuId) {
        sysPermMapper.delete(new QueryWrapper<SysPerm>().eq("menu_id", menuId));
    }

}
